package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.FindPasswordDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.FindPasswordService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author shiminghui
 * @date 2024/9/10 10:22
 * @description: TODO
 */
@Service
@RequiredArgsConstructor
public class FindPasswordServiceImpl implements FindPasswordService {

    private final XcUserMapper xcUserMapper;
    private final CheckCodeClient checkCodeClient;
    private final PasswordEncoder passwordEncoder;

    @Override
    public void findPassword(FindPasswordDto findPasswordDto) {
        //首先校验验证码
        String checkcodekey = findPasswordDto.getCheckcodekey();
        String checkcode = findPasswordDto.getCheckcode();

        if (StringUtils.isBlank(checkcodekey) || StringUtils.isBlank(checkcode)) {
            throw new RuntimeException("验证码为空");

        }
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if (!verify) {
            throw new RuntimeException("验证码输入错误");
        }


        String password = findPasswordDto.getPassword();
        String confirmpwd = findPasswordDto.getConfirmpwd();
        if (StringUtils.isBlank(password) || StringUtils.isBlank(confirmpwd)) {
            throw new RuntimeException("密码为空");
        }
        if (!password.equals(confirmpwd)) {
            throw new RuntimeException("两次密码不一致");
        }


        //校验手机号或邮箱是否存在
        String cellphone = findPasswordDto.getCellphone();
        String email = findPasswordDto.getEmail();
        if (StringUtils.isBlank(cellphone) && StringUtils.isBlank(email)) {
            throw new RuntimeException("手机号和邮箱为空");
        }

        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(cellphone), XcUser::getCellphone, cellphone);
        queryWrapper.eq(StringUtils.isNotBlank(email), XcUser::getEmail, email);
        XcUser xcUser = xcUserMapper.selectOne(queryWrapper);
        if (xcUser == null) {
            throw new RuntimeException("用户不存在");
        }

        //密码加密
        String encode = passwordEncoder.encode(password);
        xcUser.setPassword(encode);

        //修改用户密码
        xcUserMapper.updateById(xcUser);

    }
}
